// ********************************
// 爬取指定一首歌的评论
const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        ignoreDefaultArgs: ['--enable-automation'],
        defaultViewport: {
            width: 1200,
            height: 900
        }
    })
    const page = await browser.newPage()
    // 网易云音乐飙升榜
    await page.goto('https://music.163.com/#/song?id=1363071413', { waitUntil: "networkidle0" })
    // 页面内部的 frame
    const contentFrame1 = await page.frames().find(f => f.name() === 'contentFrame');
    const totalPage = await contentFrame1.evaluate(() => {
        let ele = document.querySelector("div.u-page a:nth-last-child(2)");
        return parseInt(ele.textContent);
    });
    let musics = []
    for (let i = 1; i <= totalPage; i++) {
        await contentFrame1.waitForSelector("div.itm")
        const temp = await contentFrame1.evaluate(() => {
            var list = [...document.querySelectorAll('div.itm')]
            return list.map(el => {
                const avatar = el.querySelector("a > img").src
                const profile = el.querySelector(".cnt a").href
                const nickname = el.querySelector(".cntwrap .s-fc7").textContent
                const content = el.querySelector(".cnt").textContent.replace(nickname + "：", "")
                const createTime = el.querySelector(".rp div.time").textContent;
                let countText = el.querySelector(".rp a").textContent.trim();
                let likesCount = 0;
                if (countText.length > 0) {
                    likesCount = parseInt(countText.replace(/[()]/g, ""))
                }
                return { avatar, profile, nickname, content, createTime, likesCount };
            })
        })
        musics = musics.concat(temp);
        await contentFrame1.waitForSelector('.znxt')
        await contentFrame1.click('.znxt')
    }
    fs.writeFileSync("./data.json", JSON.stringify(musics))

    await browser.close()
});

// 分析数据
Array.prototype.distinct = function () {
    let newArr = [...this];
    this.length = 0;
    for (let item of newArr) {
        if (this.findIndex(ele => ele.content === item.content) === -1) {
            this.push(item);
        }
    }
};
(() => {
    const content = fs.readFileSync("./data.json");
    const list = JSON.parse(content);
    // 筛选出点赞大于 500 评论
    let result = list.filter(ele => ele.likesCount > 500);
    result.sort((a, b) => b.likesCount - a.likesCount);
    result.distinct();
    fs.writeFileSync('./result.json',JSON.stringify(result));
})();


